from flask import Blueprint, request, jsonify
from .Cmod import *
from .Cmod_pic import *
from .Cmod_user import *
from .Cmod_express import *

blue_show = Blueprint('show', __name__)


# 产品包
@blue_show.route('/api/index/products', methods=['POST', 'GET'])
def get_product():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    # 查询数据库中的所有产品数据
    products = Product.query.all()
    data = request.json()
    page_num = int(data.get('page_num', 0))
    # 将产品数据转换为字典列表
    products_data = [
        {
            'product_id': product.product_id,
            'product_type': product.product_type,
            'product_type_id': product.product_type_id,
            'product_name': product.product_name,
            'product_details': product.product_details,
            'product_picture': product.product_picture,
            'product_music_address': product.product_music_address,
            'product_video_address': product.product_video_address,
            'product_price': product.product_price,
            'product_evalute': product.product_evalute
        } for product in products
    ]

    if page_num:
        page_now = int(data.get('page', 1)- 1) * page_num
        num = inquire_total_page(len(products_data), page_num)
        if page_now >= len(products_data):
            products_data = []
        else:
            products_data = get_page_data(products_data, data.get('page', 1), page_num)

        response = {
            "data": products_data,
            "total_page": num
        }
        print("产品数据分页发送")
        return jsonify(response), 200
    # 将产品数据作为JSON响应发送
    response = {
        'data': products_data
    }
    print("产品数据发送")
    return jsonify(response), 200


# 问题接口
@blue_show.route('/api/index/questions', methods=['POST', 'GET'])
def get_question():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    data = request.get_json()
    user_id = data.get('id')
    page_num = int(data.get('page_num', 0))

    # 查询数据库中的所有问题数据
    questions = Questions.query.all()
    # 如果有黑名单上的用户id就不发送给前端
    blacklist_id = Blacklist.query.filter_by(blacklist_parent=user_id).all()
    blacklist_id_list = [blacklist_id.blacklist_child for blacklist_id in blacklist_id]
    questions_data = []
    for question in questions:
        if question.question_user not in blacklist_id_list:
            # 查询当前项目的评论数量
            review_count = count_review(question.question_id, 'question')
            # 查询当前点赞数量
            like_count = count_like(question.question_id, 'question')
            # 查询当前项目的收藏数量
            collect_count = count_collect(question.question_id, 'question')
            tag_list = search_object_tag(question.question_id, 'question')

            questions_data.append({
                "question_id": question.question_id,
                "question_user": question.question_user,
                "question_title": question.question_title,
                "question_text": question.question_text,
                "question_integral": question.question_integral,
                "question_answer": question.question_answer,
                "question_time": question.question_time.strftime('%Y-%m-%d %H:%M:%S'),
                "review_count": review_count,
                "like_count": like_count,
                "collect_count": collect_count,
                'tag_list': tag_list
            })
    if page_num:
        page_now = int(data.get('page', 1)-1) * page_num
        num = inquire_total_page(len(questions_data), page_num)
        if page_now >= len(questions_data):
            questions_data = []
        else:
            questions_data = get_page_data(questions_data, data.get('page', 1), page_num)

        # 将问题数据作为JSON响应发送
        response = {
            "data": questions_data,
            "total_page": num
        }
        print("问题数据分页发送")
        return jsonify(response), 200
    # 将问题数据作为JSON响应发送
    response = {
        'data': questions_data,

    }
    print("问题数据发送")
    return jsonify(response), 200


# 专栏接口
@blue_show.route('/api/index/special', methods=['POST', 'GET'])
def get_special():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    # 查询数据库中的所有专栏数据
    data = request.get_json()
    user_id = data.get('id')
    page_num = int(data.get('page_num', 0))
    specials = Special.query.all()
    # 如果有黑名单上的用户id就不发送给前端
    blacklist_id = Blacklist.query.filter_by(blacklist_parent=user_id).all()
    blacklist_id_list = [blacklist_id.blacklist_child for blacklist_id in blacklist_id]
    specials_data = []
    for special in specials:
        if special.special_user not in blacklist_id_list:
            # specials_data.append(special)
            # 查询当前项目的评论数量
            review_count = count_review(special.special_id, 'special')
            # 查询当前点赞数量
            like_count = count_like(special.special_id, 'special')
            # 查询当前项目的收藏数量
            collect_count = count_collect(special.special_id, 'special')
            specials_data.append({
                'special_id': special.special_id,
                'special_user': special.special_user,
                'special_title': special.special_title,
                'special_time': special.special_time.strftime('%Y-%m-%d %H:%M:%S'),
                'review_count': review_count,
                'like_count': like_count,
                'collect_count': collect_count
            })
    if page_num:
        page_now = int(data.get('page', 1)-1) * page_num
        num = inquire_total_page(len(specials_data), page_num)

        if page_now >= len(specials_data):
            specials_data = []
        else:

            specials_data = get_page_data(specials_data, data.get('page', 1), page_num)

        response = {
            'data': specials_data,
            'total_page': num

        }
        print("专栏数据发送")
        return jsonify(response), 200
    # 将专栏数据作为JSON响应发送
    response = {
        'data': specials_data
    }
    print("专栏数据发送")
    return jsonify(response), 200


# 渲染专栏下的动态
@blue_show.route('/api/special/spdy', methods=['POST', 'GET'])
def get_spdy():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    data = request.get_json()
    user_id = data.get('id')
    special_id = data.get('special_id')
    page_num = int(data.get('page_num', 0))
    spdys = SpDy.query.filter_by(spdy_father=special_id).all()
    # 如果有黑名单上的用户id就不发送给前端
    blacklist_id = Blacklist.query.filter_by(blacklist_parent=user_id).all()
    blacklist_id_list = [blacklist_id.blacklist_child for blacklist_id in blacklist_id]
    spdys_data = []
    for spdy in spdys:
        if spdy.spdy_user not in blacklist_id_list:
            # 查询当前项目的评论数量
            review_count = count_review(spdy.spdy_id, 'special')
            # 查询当前点赞数量
            like_count = count_like(spdy.spdy_id, 'special')
            # 查询当前项目的收藏数量
            collect_count = count_collect(spdy.spdy_id, 'special')
            spdys_data.append({
                'spdy_id': spdy.spdy_id,
                'spdy_user': spdy.spdy_user,
                'spdy_title': spdy.spdy_title,
                'spdy_father': spdy.spdy_father,
                'spdy_text': spdy.spdy_text,
                'spdy_time': spdy.spdy_time.strftime('%Y-%m-%d %H:%M:%S'),
                'review_count': review_count,
                'like_count': like_count,
                'collect_count': collect_count
            })
    if page_num:
        page_now = int(data.get('page', 1)-1) * page_num
        num = inquire_total_page(len(spdys_data), page_num)
        if page_now >= len(spdys_data):
            spdys_data = []
        else:
            spdys_data = get_page_data(spdys_data, data.get('page', 1), page_num)

        response = {
            'data': spdys_data,
            'total_page': num

        }
        print("专栏下的动态数据发送")
        return jsonify(response), 200

    # 将专栏下的动态数据转换为字典列表
    response = {
        'data': spdys_data
    }
    print("专栏下的动态数据发送")
    return jsonify(response), 200


# 渲染所有文章接口
@blue_show.route('/api/index/dynamic', methods=['POST', 'GET'])
def get_article():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    # 查询数据库中的所有文章数据
    data = request.get_json()
    user_id = int(data.get('id'))
    page_num = int(data.get('page_num', 0))
    articles = Dynamic.query.all()
    # 如果有黑名单上的用户id就不发送给前端
    blacklist_id = Blacklist.query.filter_by(blacklist_parent=user_id).all()
    blacklist_id_list = [blacklist_id.blacklist_child for blacklist_id in blacklist_id]

    dynamic_data = []
    for dynamic in articles:
        if dynamic.dynamic_user not in blacklist_id_list:
            # 查询当前项目的评论数量
            review_count = count_review(dynamic.dynamic_id, 'dynamic')
            # 查询当前点赞数量
            like_count = count_like(dynamic.dynamic_id, 'dynamic')
            # 查询当前项目的收藏数量
            collect_count = count_collect(dynamic.dynamic_id, 'dynamic')
            user_now = Users.query.filter_by(user_id=dynamic.dynamic_user).first()

            for_pic = Picture.query.filter_by(picture_ob_type='user',
                                              picture_object=user_now.user_id).first()
            tag_list = TagRelation.query.filter_by(tagrelation_type='dynamic',
                                                   tagrelation_object=dynamic.dynamic_id).all()
            tag_data = []
            for tag in tag_list:
                tag_now = Tag.query.filter_by(tag_id=tag.tagrelation_tag_id).first()
                tag_data.append(tag_now.tag_name)
            dynamic_pic = Picture.query.filter_by(picture_ob_type='dynamic',
                                                  picture_object=dynamic.dynamic_id).all()
            if dynamic_pic is not None:
                dynamic_pic_list = [
                    {
                        'picture_address': dynamic_pic_now.picture_address
                    } for dynamic_pic_now in dynamic_pic
                ]
            else:
                dynamic_pic_list = []
            is_attention = is_followed(user_id, dynamic.dynamic_user)
            dynamic_data.append({
                "dynamic_id": dynamic.dynamic_id,
                "dynamic_user": dynamic.dynamic_user,
                "dynamic_title": dynamic.dynamic_title,
                "dynamic_text": dynamic.dynamic_text,
                "dynamic_time": dynamic.dynamic_time.strftime('%Y-%m-%d %H:%M:%S'),
                "review_count": review_count,
                "like_count": like_count,
                "collect_count": collect_count,
                "for_pic": for_pic.picture_address,
                "user_name": user_now.user_name,
                "user_city": user_now.user_city,
                "user_province": user_now.user_province,
                "user_grade": user_now.user_grade,
                "tag_list": tag_data,
                "dynamic_pic_list": dynamic_pic_list,
                "is_attention": is_attention
            })
    if page_num:
        page_now = int(data.get('page', 1)-1) * page_num
        num = inquire_total_page(len(dynamic_data), page_num)

        if page_now >= len(dynamic_data):
            dynamic_data = []
        else:

            dynamic_data = get_page_data(dynamic_data, data.get('page', 1), page_num)

        response = {
            "data": dynamic_data,
            "total_page": num
        }
        print("文章数据分页发送")
        return jsonify(response), 200
    # 将文章数据作为JSON响应发送

    response = {
        "data": dynamic_data
    }
    print("文章数据发送")
    return jsonify(response), 200


# 渲染各个模块下的评论区
@blue_show.route('/api/show/review', methods=['POST', 'GET'])
def get_review():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    data = request.get_json()
    object_type = data.get('object_type')
    object_id = data.get('object_id')
    reviews = Review.query.filter_by(review_object_type=object_type,
                                     review_object_id=object_id).all()
    reviews_data = []
    for review in reviews:
        # 查询当前点赞数量
        like_count = count_like(review.review_id, 'review')
        user_now = Users.query.filter_by(user_id=review.review_user).first()
        user_pic_now = Picture.query.filter_by(picture_ob_type='user', picture_object=user_now.user_id).first()
        reviews_now = {
            'review_id': review.review_id,
            'review_object_type': review.review_object_type,
            'review_object_id': review.review_object_id,
            'review_grade_top': review.review_grade_top,
            'review_top_id': review.review_top_id,
            'review_user': review.review_user,
            'review_text': review.review_text,
            'review_backer': review.review_backer,
            'review_time': review.review_time.strftime('%Y-%m-%d %H:%M:%S'),
            'like_count': like_count,
            'user_name': user_now.user_name,
            'user_introduce': user_now.user_introduce,
            'user_pic': user_pic_now.picture_address
        }
        reviews_data.append(reviews_now)
    # 如果为问题的评论区渲染，则将被采纳的评论的id发送给前端
    if object_type == "question":
        que = Questions.query.filter_by(question_id=object_id).first()

        if que.question_answer:
            qtr = QuestionRelation.query.filter_by(querelation_object=object_id).all()
            answer_id = [
                {
                    'querelation_review': question.querelation_review,
                    'querelation_number': question.querelation_number
                } for question in qtr
            ]
            response = {
                'data': reviews_data,
                'answer_id': answer_id
            }
            print("评论数据发送")
            return jsonify(response)
    response = {
        'data': reviews_data
    }
    print("评论数据发送")
    return jsonify(response), 200


# 热点问题
@blue_show.route('/api/hot/question', methods=['POST', 'GET'])
def get_hot_question():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    # 查询数据库中的所有问题数据
    questions = Questions.query.all()
    # 从questions中提取question_id放入列表中
    questions_id_list = [question.question_id for question in questions]
    questions_num = []
    for questions_id in questions_id_list:
        # 查询数据库中的所有评论数据
        rev = Review.query.filter_by(review_object_type='question',
                                    review_object_id=questions_id)
        # 查询当前项目的评论数量
        review_count = count_review(questions_id, 'question')
        # 查询当前点赞数量
        like_count = count_like(questions_id, 'question')
        # 查询当前项目的收藏数量
        collect_count = count_collect(questions_id, 'question')
        response1 = {
            'question_id': questions_id,
            'review_count': review_count,
            'like_count': like_count,
            'collect_count': collect_count
        }
        questions_num.append(response1)
    questions_data = []
    for question in questions:
        questions_data.append({
            "question_id": question.question_id,
            "question_user": question.question_user,
            "question_title": question.question_title,
            "question_text": question.question_text,
            "question_integral": question.question_integral,
            "question_answer": question.question_answer,
            "question_time": question.question_time.strftime('%Y-%m-%d %H:%M:%S')
        })
    questions_num.sort(key=lambda x: x['review_count'], reverse=True)
    response = {
        'questions_num': questions_num,
        'questions': questions_data
    }
    return jsonify(response), 200


# 热点讨论
@blue_show.route('/api/hot/dynamic', methods=['POST', 'GET'])
def get_hot():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    # 查询数据库中的所有热点讨论数据
    dyn = Dynamic.query.all()
    # 从dyn中提取dynamic_id放入列表中
    dyn_id_list = [dynamic.dynamic_id for dynamic in dyn]
    dyn_num = []
    for dyn_id in dyn_id_list:
        # 查询数据库中的所有评论数据
        rev = Review.query.filter_by(review_object_type='dynamic',
                                    review_object_id=dyn_id)
        # 查询当前项目的评论数量
        review_count = count_review(dyn_id, 'dynamic')
        # 查询当前点赞数量
        like_count = count_like(dyn_id, 'dynamic')
        # 查询当前项目的收藏数量
        collect_count = count_collect(dyn_id, 'dynamic')
        response1 = {
            'dynamic_id': dyn_id,
            'review_count': review_count,
            'like_count': like_count,
            'collect_count': collect_count
        }
        dyn_num.append(response1)
    dyn_num.sort(key=lambda x: x['review_count'], reverse=True)
    dynamic_data = []
    for dynamic in dyn:
        # 查询当前项目的评论数量
        review_count = count_review(dynamic.dynamic_id, 'dynamic')
        # 查询当前点赞数量
        like_count = count_like(dynamic.dynamic_id, 'dynamic')
        # 查询当前项目的收藏数量
        collect_count = count_collect(dynamic.dynamic_id, 'dynamic')
        user_now = Users.query.filter_by(user_id=dynamic.dynamic_user).first()

        for_pic = Picture.query.filter_by(picture_ob_type='user',
                                          picture_object=user_now.user_id).first()
        tag_list = TagRelation.query.filter_by(tagrelation_type='dynamic',
                                               tagrelation_object=dynamic.dynamic_id).all()
        tag_data = []
        for tag in tag_list:
            tag_now = Tag.query.filter_by(tag_id=tag.tagrelation_tag_id).first()
            tag_data.append(tag_now.tag_name)
        dynamic_pic = Picture.query.filter_by(picture_ob_type='dynamic',
                                              picture_object=dynamic.dynamic_id).all()
        if dynamic_pic is not None:
            dynamic_pic_list = [
                {
                    'picture_address': dynamic_pic_now.picture_address
                } for dynamic_pic_now in dynamic_pic
                ]
        else:
            dynamic_pic_list = []
        dynamic_data.append({
                "dynamic_id": dynamic.dynamic_id,
                "dynamic_user": dynamic.dynamic_user,
                "dynamic_title": dynamic.dynamic_title,
                "dynamic_text": dynamic.dynamic_text,
                "dynamic_time": dynamic.dynamic_time.strftime('%Y-%m-%d %H:%M:%S'),
                "review_count": review_count,
                "like_count": like_count,
                "collect_count": collect_count,
                "for_pic": for_pic.picture_address,
                "user_name": user_now.user_name,
                "user_city": user_now.user_city,
                "user_province": user_now.user_province,
                "user_grade": user_now.user_grade,
                "tag_list": tag_data,
                "dynamic_pic_list": dynamic_pic_list
            })
    response = {
        'dyn_num': dyn_num,
        'dynamic': dynamic_data

    }
    return jsonify(response), 200


# 根据粉丝数，来排行的用户名单
@blue_show.route('/api/hot/user_list', methods=['POST', 'GET'])
def query_user_rank():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    user_ids = db.session.query(Users.user_id).all()
    user_ids_list1 = [user_id[0] for user_id in user_ids]

    user_ids_list = []
    for user_id in user_ids_list1:
        num = db.session.query(AttentionFan).filter_by(af_child=user_id).count()
        response1 = {
            'user_id': user_id,
            'num': num,
        }
        user_ids_list.append(response1)
    user_ids_list.sort(key=lambda x: x['num'], reverse=True)

    response = {
        'user_ids_list': user_ids_list
    }
    return jsonify(response), 200


# 标签包
@blue_show.route('/api/index/tags', methods=['POST', 'GET'])
def get_tag():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    # 查询数据库中的所有标签数据
    tags = Tag.query.all()
    data = request.get_json()
    page_num = int(data.get('page_num', 0))
    tags_data = []
    for tag in tags:
        tag_id = tag.tag_id
        textpag1 = TagRelation.query.filter_by(tagrelation_object=tag_id, tagrelation_type="program").all()
        textpag2 = TagRelation.query.filter_by(tagrelation_object=tag_id, tagrelation_type="dynamic").all()
        pro_num = len(textpag1)
        dym_num = len(textpag2)
        tag_data1 = {
            'pro_num': pro_num,
            'dym_num': dym_num,
            'tag_name': tag.tag_name,
            'tag_id': tag.tag_id,
            'tag_time': tag.tag_time.strftime('%Y-%m-%d %H:%M:%S')
        }

        tags_data.append(tag_data1)
    num1 = len(tags_data)
    if page_num:
        page_now = int(data.get('page', 1)-1) * page_num
        num = inquire_total_page(num1, page_num)

        if page_now >= len(tags_data):
            tags_data = []
        else:

            tags_data = get_page_data(tags_data, data.get('page', 1), page_num)

        response = {
            'tags_data': tags_data,
            'total_page': inquire_total_page(num1, int(page_num)),
            'data_num': num,
            "num": num1
        }
        return jsonify(response)
    response = {
        'tags_data': tags_data,
        'data_num': len(tags_data),
        "num": num1
    }
    print("标签数据发送")
    return jsonify(response), 200


# 标签包，其下图片，作者头像，该项目详情
# 查询书架得得到其下文章的标签包，详情
# 渲染某篇文章
@blue_show.route('/api/show/dynamic', methods=['POST', 'GET'])
def get_article_detail():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    data = request.get_json()
    object_id = data.get('object_id')

    dynamic = Dynamic.query.filter_by(dynamic_id=object_id).first()
    dynamic_now = {
        'dynamic_id': dynamic.dynamic_id,
        'dynamic_user': dynamic.dynamic_user,
        'dynamic_text': dynamic.dynamic_text,
        'dynamic_title': dynamic.dynamic_title,
        'dynamic_time': dynamic.dynamic_time.strftime('%Y-%m-%d %H:%M:%S'),
        'dynamic_see': dynamic.dynamic_see
    }
    pics = Picture.query.filter_by(picture_ob_type='dynamic', picture_object=object_id).all()
    pics_list = [
        {
            'picture_address': pic.picture_address
        } for pic in pics
    ]
    user_pics = Picture.query.filter_by(picture_ob_type='user', picture_object=dynamic.dynamic_user).first()
    tag_list = search_object_tag(object_id, 'dynamic')
    response = {
        'dynamic_now': dynamic_now,
        'pics_list': pics_list,
        'user_pics': user_pics.picture_address,
        'tag_list': tag_list
    }
    return jsonify(response), 200


# 渲染某个书架
@blue_show.route('/api/show/bookshelf', methods=['POST', 'GET'])
def get_bookshelf():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    data = request.get_json()
    object_id = data.get('object_id')
    dynamic_id_list = [dynamic_id for dynamic_id, in Bookrelation.query.with_entities(
        Bookrelation.bookrelation_dynamic_id
    ).filter_by(bookrelation_bookshelf_id=object_id).all()]
    dynamic_list = []
    for dynamic_id in dynamic_id_list:
        print(dynamic_id)
        dynamic_now = Dynamic.query.filter_by(dynamic_id=dynamic_id).first()
        tag_list = search_object_tag(dynamic_now.dynamic_id, 'dynamic')
        user_pics = Picture.query.filter_by(picture_ob_type='user',
                                            picture_object=dynamic_now.dynamic_user).first()
        dynamic_now_data = {
            'dynamic_id': dynamic_now.dynamic_id,
            'dynamic_user': dynamic_now.dynamic_user,
            'dynamic_text': dynamic_now.dynamic_text,
            'dynamic_title': dynamic_now.dynamic_title,
            'dynamic_time': dynamic_now.dynamic_time.strftime('%Y-%m-%d %H:%M:%S'),
            'dynamic_see': dynamic_now.dynamic_see,
            'tag_list': tag_list,
            'auth_pic': user_pics.picture_address
        }
        dynamic_list.append(dynamic_now_data)
    response = {
        'dynamic_list': dynamic_list
    }
    return jsonify(response), 200


# 渲染某个问题
@blue_show.route('/api/show/question', methods=['POST', 'GET'])
def get_question_detail():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    data = request.get_json()
    object_id = data.get('object_id')
    question = Questions.query.filter_by(question_id=object_id).first()
    question_now = {
        'question_id': question.question_id,
        'question_user': question.question_user,
        'question_title': question.question_title,
        'question_text': question.question_text,
        'question_integral': question.question_integral,
        'question_answer': question.question_answer,
        'question_time': question.question_time.strftime('%Y-%m-%d %H:%M:%S'),
        'question_see': question.question_see
    }
    if question.question_answer != 0:
        question_answer = QuestionRelation.query.filter_by(querelation_object=object_id).all()
        question_answer_list = [
            {
                'querelation_review': question_answer_now.querelation_review,
                'querelation_number': question_answer_now.querelation_number
            } for question_answer_now in question_answer
        ]
    else:
        question_answer_list = []

    user_pics = Picture.query.filter_by(picture_ob_type='user', picture_object=question.question_user).first()
    tag_list = search_object_tag(object_id, 'question')

    response = {
        'question_now': question_now,
        'user_pics': user_pics.picture_address,
        'tag_list': tag_list,
        'question_answer_list': question_answer_list
    }
    return jsonify(response), 200






